package org.litepal.crud;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;

import org.litepal.crud.model.AssociationInfo;
import org.litepal.util.Const;

public class Many2ManyAnalyzer extends AssociationsAnalyzer {

	@SuppressWarnings("unchecked")
	void analyze(DataSupport baseObj, AssociationInfo associationInfo) throws SecurityException,
			IllegalArgumentException, NoSuchMethodException, IllegalAccessException,
			InvocationTargetException {
		Collection<DataSupport> selfGetMethodValue = (Collection<DataSupport>) takeGetMethodValueByField(
				baseObj, associationInfo.getAssociateOtherModelFromSelf());
		if (selfGetMethodValue != null) {
			for (DataSupport associatedModel : selfGetMethodValue) {
				Collection<DataSupport> associatedGetMethodValue = (Collection<DataSupport>) takeGetMethodValueByField(
						associatedModel, associationInfo.getAssociateSelfFromOtherModel());
				if (!associatedGetMethodValue.contains(baseObj)) {
					associatedGetMethodValue.add(baseObj);
				}
				baseObj.addNewAssociatedModel(associatedModel, Const.Model.MANY_TO_MANY, false);
				associatedModel.addNewAssociatedModel(baseObj, Const.Model.MANY_TO_MANY, false);
			}
		}
		// if (associatedModel != null) {
		// Collection<DataSupport> associatedModels = (Collection<DataSupport>)
		// takeGetMethodValueByField(
		// associatedModel, associationInfo.getAssociateSelfFromOtherModel());
		// if (associatedModels == null) {
		// associatedModels = new ArrayList<DataSupport>();
		// }
		// associatedModels.add(baseObj);
		// baseObj.addNewAssociatedModel(associatedModel,
		// Const.Model.MANY_TO_MANY, false);
		// associatedModel.addNewAssociatedModel(baseObj,
		// Const.Model.MANY_TO_MANY, false);
		// }
	}
}
